package com.itqf.ipmsys.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.itqf.ipmsys.constants.ShiroConstant;
import com.itqf.ipmsys.entity.Admin;
import com.itqf.ipmsys.entity.Police;
import com.itqf.ipmsys.mapper.AdminMapper;
import com.itqf.ipmsys.service.AdminService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.apache.shiro.authc.credential.HashedCredentialsMatcher;
import org.apache.shiro.crypto.hash.SimpleHash;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;

/**
 * <p>
 * 管理员表 服务实现类
 * </p>
 *
 * @author corn
 * @since 2021-09-22
 */
@Service
public class AdminServiceImpl extends ServiceImpl<AdminMapper, Admin> implements AdminService {

    @Autowired
    private AdminMapper adminMapper;
    /**
     * 根据账户查询管理员
     *
     * @param account
     * @return
     */
    @Override
    public Admin findAdminByAccount(String account) {
        Admin admin = adminMapper.selectOne(new QueryWrapper<Admin>().eq("account", account));
        return admin;
    }

    /**
     * 修改管理员登录信息
     *
     * @param id
     * @param ip
     * @param date
     * @return
     */
    @Override
    public int updateAdminById(Integer id, String ip, Date date) {
        Admin admin = new Admin();

        admin.setId(id);
        admin.setLastLoginIp(ip);
        admin.setLastLoginTime(date);
        int rows = adminMapper.updateById(admin);
        return rows;
    }

    /**
     * 重置密码
     *
     * @param police
     * @return
     */
    @Override
    public int resetPassword(Police police) {
        //1. 定义默认密码
        String hash = "123456";
        //2. 设置加密方式,盐,加密次数等,获取加密后的密匙
        SimpleHash simpleHash = new SimpleHash("md5", hash, ShiroConstant.ADMIN_SALT,6);
        String bytes = simpleHash.toString();
        //3. 将得到的密匙封装进实体类
        Admin admin = new Admin();
        admin.setPassword(bytes);
        admin.setUpdateTime(new Date());
        //4. 创建更新条件
        UpdateWrapper<Admin> updateWrapper =new UpdateWrapper<>();
        updateWrapper.eq("account", police.getId());
        //5. 执行并返回结果
        return adminMapper.update(admin, updateWrapper);
    }
}
